<?php
use service\DataService;
use service\NodeService;
use think\Db;

/**
 * 打印输出数据到文件
 * @param mixed $data 输出的数据
 * @param bool $force 强制替换
 * @param string|null $file
 */
function p($data, $force = false, $file = null)
{
    is_null($file) && $file = env('runtime_path') . date('Ymd') . '.txt';
    $str = (is_string($data) ? $data : (is_array($data) || is_object($data)) ? print_r($data, true) : var_export($data, true)) . PHP_EOL;
    $force ? file_put_contents($file, $str) : file_put_contents($file, $str, FILE_APPEND);
}

/**
 * RBAC节点权限验证
 * @param string $node
 * @return bool
 */
function auth($node)
{
    return NodeService::checkAuthNode($node);
}

/**
 * 设备或配置系统参数
 * @param string $name 参数名称
 * @param bool $value 默认是null为获取值，否则为更新
 * @return string|bool
 * @throws \think\Exception
 * @throws \think\exception\PDOException
 */
function sysconf($name, $value = null)
{
    static $config = [];
    if ($value !== null) {
        list($config, $data) = [[], ['name' => $name, 'value' => $value]];
        return DataService::save('SystemConfig', $data, 'name');
    }
    if (empty($config)) {
        $config = Db::name('SystemConfig')->column('name,value');
    }
    return isset($config[$name]) ? $config[$name] : '';
}

/**
 * 日期格式标准输出
 * @param string $datetime 输入日期
 * @param string $format 输出格式
 * @return false|string
 */
function format_datetime($datetime, $format = 'Y年m月d日 H:i:s')
{
    return date($format, strtotime($datetime));
}

/**
 * UTF8字符串加密
 * @param string $string
 * @return string
 */
function encode($string)
{
    list($chars, $length) = ['', strlen($string = iconv('utf-8', 'gbk', $string))];
    for ($i = 0; $i < $length; $i++) {
        $chars .= str_pad(base_convert(ord($string[$i]), 10, 36), 2, 0, 0);
    }
    return $chars;
}

/**
 * UTF8字符串解密
 * @param string $string
 * @return string
 */
function decode($string)
{
    $chars = '';
    foreach (str_split($string, 2) as $char) {
        $chars .= chr(intval(base_convert($char, 36, 10)));
    }
    return iconv('gbk', 'utf-8', $chars);
}

/**
 * 下载远程文件到本地
 * @param string $url 远程图片地址
 * @return string
 */
function local_image($url)
{
    return \service\FileService::download($url)['url'];
}

function pp($data){
    if (is_bool($data)){
        var_dump($data);
    }else{
        echo '<pre>';
        print_r($data);
    }
}

//config表查询
function conf($name, $value = null)
{
    static $conf = [];
    if ($value !== null) {
        list($conf, $data) = [[], ['name' => $name, 'value' => $value]];
        return DataService::save('Config', $data, 'name');
    }
    if (empty($conf)) {
        $conf = Db::name('Config')->column('name,value');
    }
    return isset($conf[$name]) ? $conf[$name] : '';
}

//setting表查询
function setting($name,$field='value')
{
    $setting = Db::name('Setting')->where('name',$name)->value($field);
    return $setting;
}

//接口返回
function re_msg($code,$msg=''){
    return json_encode(['code'=>$code,'msg'=>$msg],320);
}

//随机数32位
function getRandChar($length)
{
    $str = null;
    $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
    $max = strlen($strPol) - 1;

    for ($i = 0;
         $i < $length;
         $i++) {
        $str .= $strPol[rand(0, $max)];
    }
    return $str;
}

//生成订单号
function makeOrderNo(){
    $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
    $orderSn =
        $yCode[intval(date('Y')) - 2017] . strtoupper(dechex(date('m'))) . date(
            'd') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf(
            '%02d', rand(0, 99));
    return $orderSn;
}

//时间段
function total($type,$c=false) {
    switch ($type) {
        case 3: { // 本月
            $start=mktime(0,0,0,date('m'),1,date('Y'));
            $end=mktime(0,0,0,date('m'),date('d')+1,date('Y'));
        };break;
        case 6: { //上月
            $start = mktime(0,0,0,date('m')-1,1,date('Y'));
            $end = mktime(0,0,0,date('m'),1,date('Y'))-1;
        };break;
        case 7: { //本周
            $start = mktime(0,0,0,date('m'),date('d')-date('w'),date('Y'));
            $end = mktime(0,0,0,date('m'),date('d'),date('Y'));
        };break;
        case 8: { //上周
            $start = mktime(0,0,0,date('m'),date('d')-7-date('w'),date('Y'));
            $end = mktime(0,0,0,date('m'),date('d')-date('w'),date('Y'))-1;
        };break;
        case 4: { // 本年
            $start = mktime(0,0,0,1,1,date('Y'));
            $end = mktime(0,0,0,1,1,date('Y')+1);
        };break;
        case 5: { // 昨天
            $start = mktime(0,0,0,date('m'),date('d')-1,date('Y'));
            $end = mktime(0,0,0,date('m'),date('d'),date('Y'))-1;
        };break;
        case 9: { // 前七天
            $start = mktime(0,0,0,date('m'),date('d')-6,date('Y'));
            $end = mktime(date('H'),date('m'),date('s'),date('m'),date('d'),date('Y'));
        };break;
        case 10: { // 本季度
            $season = ceil((date('n'))/3);//当月是第几季度
            $start =mktime(0, 0, 0,$season*3-3+1,1,date('Y'));
            $end = mktime(23,59,59,$season*3,date('t',mktime(0, 0 , 0,$season*3,1,date("Y"))),date('Y'));
        };break;
        case 2: { // 前30天
            $start = mktime(0,0,0,date('m'),date('d')-29,date('Y'));
            $end = mktime(date('H'),date('m'),date('s'),date('m'),date('d'),date('Y'));
        };break;
        case 1: { // 今天
            $start = mktime(0,0,0,date('m'),date('d'),date('Y'));
            $end = mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
        };break;
        default:{
            return '';
        }

    }
    if ($c){
        return [date('Y-m-d H:i:s',$start),date('Y-m-d H:i:s',$end)];
    }
    return " BETWEEN '" . date('Y-m-d H:i:s',$start) . "' AND '" . date('Y-m-d H:i:s',$end) . "'";
}

function preg_phone($phone) {
    if(preg_match("/^1[345789]\d{9}$/", $phone)) {
        return true;
    } else {
        return false;
    }
}

function jumpUrl($url){
    list($base, $spm) = [url('@admin'), input('get.spm')];
    return "{$base}#{$url}?spm={$spm}";
}

/**
 * 计算两点地理坐标之间的距离
 * @param  Decimal $longitude1 起点经度
 * @param  Decimal $latitude1  起点纬度
 * @param  Decimal $longitude2 终点经度
 * @param  Decimal $latitude2  终点纬度
 * @param  Int     $unit       单位 1:米 2:公里
 * @param  Int     $decimal    精度 保留小数位数
 * @return Decimal
 */
function getDistance($longitude1, $latitude1, $longitude2, $latitude2, $unit=2, $decimal=2){

    $EARTH_RADIUS = 6370.996; // 地球半径系数
    $PI = 3.1415926;

    $radLat1 = $latitude1 * $PI / 180.0;
    $radLat2 = $latitude2 * $PI / 180.0;

    $radLng1 = $longitude1 * $PI / 180.0;
    $radLng2 = $longitude2 * $PI /180.0;

    $a = $radLat1 - $radLat2;
    $b = $radLng1 - $radLng2;

    $distance = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1) * cos($radLat2) * pow(sin($b/2),2)));
    $distance = $distance * $EARTH_RADIUS * 1000;

    if($unit==2){
        $distance = $distance / 1000;
    }

    return round($distance, $decimal);
}

function exportExcel($title,$tableheader,$data){
    //创建对象
    header("Content-Type:text/html;charset=utf-8");
    error_reporting(E_ALL);
    ini_set('display_errors', TRUE);
    ini_set('display_startup_errors', TRUE);
    $excel = new PHPExcel();
    $letter = array(
        'A','B','C','D','E','F','G','H','I','J','K','L','M',
        'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
        'AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM',
        'AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ'
    );
    //填充表头信息
    for($i = 0;$i < count($tableheader);$i++) {
        $excel->getActiveSheet()->setCellValue("$letter[$i]1","$tableheader[$i]");
    }

    //填充表格信息
    for ($i = 2;$i <= count($data) + 1;$i++) {
        $j = 0;
        foreach ($data[$i - 2] as $key=>$value) {
            $excel->getActiveSheet()->setCellValue("$letter[$j]$i","$value");
            $j++;
        }
    }
    //创建Excel输入对象
    $write = new PHPExcel_Writer_Excel5($excel);
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
    header("Content-Type:application/force-download");
    header("Content-Type:application/vnd.ms-execl");
    header("Content-Type:application/octet-stream");
    header("Content-Type:application/download");;
    header('Content-Disposition:attachment;filename="'.$title.'.xls"');

    header("Content-Transfer-Encoding:binary");
    $write->save('php://output');

}

function jiequ($data,$num){
    $len = mb_strlen($data);
    if ($len>$num){
        $str = mb_substr($data,0,$num).'...';
    }else{
        $str = $data;
    }
    return $str;
}

function newspre($id,$pid){
    $pre = Db::name('news')->where(['is_deleted'=>1,'status'=>1,'pid'=>$pid])->where('id','<',$id)->order('id asc')->limit(1)->select();
    if (!empty($pre)){
        return ['id'=>$pre[0]['id'],'title'=>$pre[0]['title']];
    }else{
        return [];
    }
}

function newsnext($id,$pid){
    $next = Db::name('news')->where(['is_deleted'=>1,'status'=>1,'pid'=>$pid])->where('id','>',$id)->order('id asc')->limit(1)->select();
    if (!empty($next)){
        return ['id'=>$next[0]['id'],'title'=>$next[0]['title']];
    }else{
        return [];
    }
}

function city_data($data=[]){
    if (!empty($data)){
        foreach ($data as $k=>$v){
            unset($data[$k]['pid']);
            $data[$k]['text'] = $v['name'];
            $data[$k]['value'] = $v['id'];
            unset($data[$k]['name']);
            unset($data[$k]['id']);
        }
        return json_encode($data, 320);
    }else{
        return '';
    }
}
